﻿using UnityEngine;
using System.Collections;

public enum TikiAnimations {
	IDLE = 0,
	WALK,
	ATTACK,
	ONFIRE,
	NUM_ANIMS
}

public class Tiki : Objective {

	public CharacterAnimation[] animations;
	public CharacterAnimator animator;
	public float speed;

	bool _isOnFire;
	bool _attacking;
	Aggro _aggro;
	AttackRange _attackRange;
	GameObject _playerObj;

	// Use this for initialization
	new void Start () {
		base.Start ();

		animator = GetComponent<CharacterAnimator> ();
		
		animator.ChangeAnimation(animations[(int)TikiAnimations.IDLE], 0);

		_attacking = false;
		_aggro = GetComponentInChildren<Aggro> ();
		_attackRange = GetComponentInChildren<AttackRange> ();

		_playerObj = GameObject.FindGameObjectWithTag ("Player");

		_isOnFire = false;
	}
	
	// Update is called once per frame
	void Update () {
		if (_attacking && !animator.isPlaying) {
			if(_attackRange.inAttackRange) {
				animator.ChangeAnimation(animations[(int)TikiAnimations.ATTACK], 0);
			} else {
				_attacking = false;
			}
		}

		if(!_isOnFire) {
			if (_aggro.isNearPlayer) {
				if(_attackRange.inAttackRange) {
					_attacking = true;
					animator.ChangeAnimation(animations[(int)TikiAnimations.ATTACK], 0);
					rigidbody2D.velocity = Vector2.zero;
				} else if (!_attacking) {
					animator.ChangeAnimation(animations[(int)TikiAnimations.WALK], 0);
					Vector2 toPlayer = _playerObj.transform.position - transform.position;
					toPlayer.Normalize();
					rigidbody2D.velocity = toPlayer * speed;
				}
			} else {
				animator.ChangeAnimation(animations[(int)TikiAnimations.IDLE], 0);
				rigidbody2D.velocity = Vector2.zero;
			}
		}
	}

	void OnCollisionStay2D(Collision2D collision) {
		if (collision.collider.tag == "Player") {
			if(collision.collider.GetComponent<Player>().isOnFire) {
				DestroyObject(this.gameObject, 2.0f);
				rigidbody2D.velocity = Vector2.zero;
				_isOnFire = true;
				rigidbody2D.collider2D.isTrigger = true;
				animator.ChangeAnimation(animations[(int)TikiAnimations.ONFIRE], 0);
				// stop Collision with player
				// Play fire death effect/animation
			}
		}
	}
}
